<?php
  include('header.php');
  include('functions.php');
  include('show_smilies.php');
  echo '<table><tr><th width="100%"><h3>' . $l_post_new_t . '</h3></th></tr></table><hr />';
  $pageTitle = "$l_create_topic";
  if ($_SESSION['signed_in'] == false) {
      //the user is not signed in
      echo '<br /><div align="center">' . $l_you_need_to . ' <a class="loginlink" href="signin.php">' . $l_login_s . '</a> ' . $l_in_order . ' <br>' . $l_u_also . ' <a class="loginlink" href="signup.php">' . $l_register_s . '</a> ' . $l_for_acc . '</div><br />';
  } else {
      //the user is signed in
      if ($_SERVER['REQUEST_METHOD'] != 'POST') {
          $qqq += 1;
          //the form hasn't been posted yet, display it
          //retrieve the categories from the database for use in the dropdown
		  
		  if ($_SESSION['user_level']<1) 
		  {
		  $condition = "WHERE cat_permission<3"; 
		  $condition2 = "AND cat_permission<3";
		  }
		  $result = $db->query("
          SELECT 
           cat_id, 
           cat_name, 
           cat_description, 
           cat_parent, 
           cat_child 
          FROM " . $table_prefix . "categories $condition");
          if (!$result) {
              //the query failed, uh-oh :-(
              echo $l_error_select_db;
          } else {
              if (mysql_num_rows($result) == 0) {
                  //there are no categories, so a topic can't be posted
                  if ($_SESSION['user_level'] == 1) {
                      echo $l_no_cat_created;
                  } else {
                      echo $l_before_post;
                  }
              } else {
                  echo '<br /><form name="myForm" method="post" action=""><b>  &nbsp; &nbsp;' . $l_subject . ': </b><br />&nbsp; &nbsp;<input maxlength="70" type="text" size="72" name="topic_subject" /><br /> <b>&nbsp; &nbsp;' . $l_category . ':</b><br />&nbsp; &nbsp;</input>';
                  
                  echo '<select name="topic_cat">';
                  while ($row = $db->fetch_array($result,'assoc')) {
                      if ($row['cat_id'] == $_GET['f']) {
                          $selected = "selected";
                      } else {
                          
                          $selected = null;
                      }
                      if ($row['cat_parent'] == 0) {
                          echo '<option disabled="disabled" value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
                          
                          $qqq += 1;
						  $result2 = $db->query("SELECT * FROM " . $table_prefix . "categories WHERE cat_parent >0 $condition2");
                      }
                      while ($row2 = $db->fetch_array($result2,'assoc')) {
                          if ($row2['cat_parent'] == $row['cat_id']) {
                              if ($row2['cat_id'] == $_GET['f']) {
                                  $selected = "selected";
                              } else {
                                  
                                  $selected = null;
                              }
                              
                              echo '<option ' . $selected . ' value = ' . $row2["cat_id"] . '>&nbsp;|- > ' . $row2["cat_name"] . '</option>';
                          }
                      }
                  }
                  echo '</select><br /><br />';
                  
                  $editor_css = "./style/$default_style/editor_reply.css";
                  $editor = "./style/$default_style/editor.js";
                  $if_smilies = "";
                              $endif_smilies = "";
                              $if_guest_post = "";
                              $endif_guest_post = "";
                              
                              if ($allow_smilies == 0) {
                                  $if_smilies = "<!--";
                                  $endif_smilies = "-->";
                                  $if_guest_post = "<!--";
                                  $endif_guest_post = "-->";
                              }
                              
                              if ($allow_smilies == 0 and $allow_guest_posts == "1") {
                                  $if_smilies = "<!--";
                                  $endif_smilies = "-->";
                                  $if_guest_post = "";
                                  $endif_guest_post = "";
                              }
                              
                              if ($allow_smilies == 1 and $allow_guest_posts == "1") {
                                  $if_smilies = "";
                                  $endif_smilies = "";
                                  $if_guest_post = "";
                                  $endif_guest_post = "";
                              }
                              
                              if ($allow_smilies == 1 and $allow_guest_posts == "0") {
                                  $if_smilies = "";
                                  $endif_smilies = "";
                                  $if_guest_post = "<!--";
                                  $endif_guest_post = "-->";
                              }
                              
                              if ($allow_smilies == 1 and $allow_guest_posts == "1" and $_SESSION['user_id'] > 1) {
                                  $if_smilies = "";
                                  $endif_smilies = "";
                                  $if_guest_post = "<!--";
                                  $endif_guest_post = "-->";
                              }
                              
                              if ($captcha_for_guests == "0") {
                                  $if_guest_post = "<!--";
                                  $endif_guest_post = "-->";
                              }
                              if ($captcha_for_guests == "1" and $_SESSION['signed_in']) {
                                  $if_guest_post = "<!--";
                                  $endif_guest_post = "-->";
                              }
                  if ($default_wysiwyg == "1") {
                      $default_editor = "";
                  }
                  if ($default_wysiwyg != "1") {
                      $default_editor = "initEditor(\"reply\", true);  SwitchEditor()";
                  }
                  if ($topic_icons == 1) {
                      echo '&nbsp;&nbsp;&nbsp;<b>' . $l_topic_icon . '</b> 
<!--<input type="radio" name="icon1" checked value="0" />&nbsp;' . $l_noone . '
| --><input type="radio" checked name="icon1" value="normal.gif" />&nbsp;<img src="./img/misc/normal.gif">
| <input type="radio" name="icon1" value="cool.gif" />&nbsp;<img src="./img/misc/cool.gif">
| <input type="radio" name="icon1" value="arrow.gif" />&nbsp;<img src="./img/misc/arrow.gif">
| <input type="radio" name="icon1" value="thumbdown.gif" />&nbsp;<img src="./img/misc/thumbdown.gif">
| <input type="radio" name="icon1" value="sad.gif" />&nbsp;<img src="./img/misc/sad.gif">
| <input type="radio" name="icon1" value="thumbup.gif" />&nbsp;<img src="./img/misc/thumbup.gif">
| <input type="radio" name="icon1" value="mrgreen.gif" />&nbsp;<img src="./img/misc/mrgreen.gif">
| <input type="radio" name="icon1" value="question.gif" />&nbsp;<img src="./img/misc/question.gif">
| <input type="radio" name="icon1" value="alert.gif" />&nbsp;<img src="./img/misc/alert.gif">
';
                  }
                  $tags = array('{Message}', '{MORE_SMILIES}', '{DISABLE_SMILIES}', '{F_ID}', '{T_ID}', '{POST_TOPIC}', '{EDITOR_CSS}', '{EDITOR}', '{WYSIWYG}', '{IF_SMILIES}', '{END_SMILIES}','(SUBMIT_REPLY)','{PREVIEW}','{DISABLE_BB}');
                  $data = array($l_message, $l_more_smilies, $l_dissmilies, mysql_real_escape_string($_GET['f']), $topicid, $l_create_topic, $editor_css, $editor, $default_editor, $if_smilies, $endif_smilies,$l_submit_reply,$l_preview_button,$l_disable_bb);
                  echo str_replace($tags, $data, file_get_contents("./style/" . $default_style . "/create_topic.html"));
              }
          }
      } else {
          $blah = $_POST["reply"];
          $blah2 = $_POST["topic_subject"];
          if (strlen($blah2) < $min_post_characters) {
              echo "<span style='color:red'><div align='center'><br />$l_subject_few<br /><br /></span>
<a href='create_topic.php'>$l_post_new_t</a></div><br/>";
          } else {
              
              $_POST["reply"] = trim($_POST["reply"]);
              
              //a real user posted a real reply
              $blah = $_POST["reply"];
              if ((strlen($blah) < $min_post_characters) or (preg_match('|^\s*\z|', $_POST["reply"]))) {
                  echo "<div align=\"center\"><span style='color:red'><br />$l_too_few_char_m<br /><br /></span>
<a href=\"#reply\" onClick='history.go(-1)'>$l_back_to_prev</a></div><br/>";
              } else {
                  $t_subject = $_POST["topic_subject"];
                  $t_subject = convEnt2($t_subject);
                  $t_subject = str_replace("\n", "\n<br>", $t_subject);
                   $t_subject = trim($t_subject);
                  //the form has been posted, so save it
                  //insert the topic into the topics table first, then we'll save the post into the posts table
                  $qqq += 1;
				  $result2 = $db->query("SELECT user_name, user_posts FROM " . $table_prefix . "users WHERE user_id =" . $_SESSION['user_id'] . "  ");
                  $username = $db->fetch_array($result2,'assoc');
                  $qqq += 1;
				  //Check if this post need to be approved
				  $topic_status = 0;
				  $approve = 0;
                  if ($post_approve == 1 AND $_SESSION['user_level']<1 AND $username['user_posts']<$auto_approve_after_posts) {$approve = 1;$topic_status = 2;}
				  if ($post_approve == 1 AND $_SESSION['user_level']<1 AND $auto_approve_after_posts == 0) {$approve = 1; $topic_status = 2;}
				  $result = $db->query("
				  INSERT INTO " . $table_prefix . "topics
				  (topic_subject,
				  topic_date, 
				  topic_cat, 
				  topic_by, 
				  topic_last_poster, 
				  topic_last_post_date, 
				  topic_starter, 
				  topic_last_poster_id,
				  topic_icon,
                  topic_status) 
				  VALUES
				  ('$t_subject',  
				  NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR, 
				  " . mysql_real_escape_string($_POST['topic_cat']) . ", 
				  $_SESSION[user_id],
				  '$username[user_name]', 
				  NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR, 
				  '$username[user_name]',
				  $_SESSION[user_id],'$_POST[icon1]',$topic_status)");
                  
                  //the first query worked, now start the second, posts query
                  //retrieve the id of the freshly created topic for usage in the posts query
                  $topicid = mysql_insert_id();
                  $text = $_POST['reply'];
				  $text = my_nl2br($text); //Remove double or miltiple new lines
                  $text = convEnt2($text);
                  $text = str_replace("\n", "\n<br>", $text);
                  $disable_smilies = "0";
                  if (isset($_POST['dissmilies']) && $_POST['dissmilies'] == 'on') {
                      $disable_smilies = "1";
                      $text = DisableSmilies($text);
                  }
                  $text = trim($text);
                  if (!isset($_POST['dissbb'])) {
                          $text = BBCode($text);
                      }
                  $userIP = $_SERVER["REMOTE_ADDR"];
				  
				  $sql = $db->query("
				  INSERT INTO " . $table_prefix . "posts
				  (post_content, 
				  post_date, 
				  post_topic, 
				  post_by, 
				  post_subject, 
				  poster_ip, 
				  post_cat,
				  post_approve) 
				  VALUES ('$text', 
				  NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR, 
				  $topicid, 
				  $_SESSION[user_id],'$t_subject',
				  '$userIP ',
				  " . mysql_real_escape_string($_POST['topic_cat']) . ", $approve)");
				  $result5 = $db->query("UPDATE " . $table_prefix . "users set user_posts=user_posts+1 WHERE user_id = " . $_SESSION['user_id'] . "");
                  $qqq += 1;
                  
                  //UPDATE categories
                  //all topics
				  $result44 = $db->query("SELECT reply FROM " . $table_prefix . "topics WHERE topic_cat = " . mysql_real_escape_string($_POST['topic_cat']) . "");
                  $topics = mysql_num_rows($result44);
                  //all replies
				  $result55 = $db->query("SELECT SUM(reply) FROM " . $table_prefix . "topics WHERE topic_cat = " . mysql_real_escape_string($_POST['topic_cat']) . "");
                  $row5 = $db->fetch_array($result55,'assoc');
                  $num_replies = $row5['SUM(reply)'];
                  
				  $result5 = $db->query("
				  UPDATE " . $table_prefix . "categories 
				  SET 
				  cat_last_post_id=$topicid, 
				  cat_last_poster_id=$_SESSION[user_id],
				  cat_last_post_subject='$t_subject',
				  cat_last_post_time = NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR, 
				  cat_last_poster_name='$_SESSION[user_name]',
				  cat_posts=$num_replies,
				  cat_topics=$topics
				  WHERE cat_id = " . mysql_real_escape_string($_POST['topic_cat']) . "") or die(mysql_error());
                  
                  //Cache this topic
                  if ($forum_cache == 1) {
                      $time = strtotime($time_difference . " hours");
                      $cache = "./cache/forum" . mysql_real_escape_string($_POST['topic_cat']) . ".php";
                      $FileHandle = fopen($cache, 'w') or die("can't open file");
                      fwrite($FileHandle, "ForumID = " . mysql_real_escape_string($_POST['topic_cat']) . "");
                      fwrite($FileHandle, "\nTopicID = " . $topicid . "");
                      fwrite($FileHandle, "\nLast Topic = " . $t_subject . "");
                      fwrite($FileHandle, "\nTopic date = " . date($date_format, $time) . "");
                      fwrite($FileHandle, "\nTopic by = " . $username['user_name'] . "");
                      fwrite($FileHandle, "\nUserID = " . $_SESSION['user_id'] . "");
                      fwrite($FileHandle, "\nTopics = " . $topics . "");
                      fwrite($FileHandle, "\nReplies = " . $num_replies . "");
                      fclose($FileHandle);
                  }
                  //Cache this topic
                  
                  $qqq += 1;
                  if (!$sql) {
                      //the query failed, uh-oh :-(
                      echo $l_error_select_db;
                  }
                  //after a lot of work, the query succeeded!
                  echo '<br /><div align="center">' . $l_post_success . '<br /><br /><a href="topic.php?t=' . $topicid . '">' . $l_goto_new . '</a>.</div><br />';
              }
          }
      }
  }
  $pageTitle = $l_create_topic;
  $pageContents = ob_get_contents();
  ob_end_clean();
  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
?>
